package it.fuzzylogics.fuzzywidgetsLibrary.client.FuzzyListeners;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Element;


public class FMouseWheelListener {

    public FMouseWheelListener(Element e, FMouseWheelHandler listener) {
        attachMouseWheelListener(e, listener);
    }

    public static void setMouseWheelListener(Element e, FMouseWheelHandler listener) {
        new FMouseWheelListener(e, listener);
    }

    private static native void dispatchMouseWheelEvent(JavaScriptObject event) /*-{
        @it.fuzzylogics.fuzzywidgetsLibrary.client.FuzzyListeners.FMouseWheelListener::dispatchMouseWheelEvent(Lcom/google/gwt/core/client/JavaScriptObject;Lit/fuzzylogics/fuzzywidgetsLibrary/client/FuzzyListeners/FMouseWheelHandler;)(event, this.__mousewheellistener);
     }-*/;


    private static native void dispatchMouseWheelEvent(JavaScriptObject event, FMouseWheelHandler listener) /*-{

         if (!event) event = $wnd.event;

         var delta = 0;
         if (event.wheelDelta){
             delta = event.wheelDelta / 120;
         }
         else if (event.detail )
         {
             delta = -event.detail / 3;
         }

         if ( delta > 0 ) {
             listener.@it.fuzzylogics.fuzzywidgetsLibrary.client.FuzzyListeners.FMouseWheelHandler::onMouseWheelUp(I)(delta);
         } else {
             listener.@it.fuzzylogics.fuzzywidgetsLibrary.client.FuzzyListeners.FMouseWheelHandler::onMouseWheelDown(I)(-delta);
         }

         if (event.preventDefault)
             event.preventDefault();
         event.returnValue = false;

    }-*/;

    private native void attachMouseWheelListener(Element e, FMouseWheelHandler listener) /*-{

           e.__mousewheellistener = listener;

           if (e.onmousewheel === undefined) {
               e.addEventListener('DOMMouseScroll', @it.fuzzylogics.fuzzywidgetsLibrary.client.FuzzyListeners.FMouseWheelListener::dispatchMouseWheelEvent(Lcom/google/gwt/core/client/JavaScriptObject;), false);
           }

           e.onmousewheel = function(event) {
               @it.fuzzylogics.fuzzywidgetsLibrary.client.FuzzyListeners.FMouseWheelListener::dispatchMouseWheelEvent(Lcom/google/gwt/core/client/JavaScriptObject;Lit/fuzzylogics/fuzzywidgetsLibrary/client/FuzzyListeners/FMouseWheelHandler;)(event, this.__mousewheellistener)
           }
    }-*/;
}